// document.writeln("<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>");
// document.writeln("<script type='text/javascript' src='https://rawgit.com/schmich/instascan-builds/master/instascan.min.js'></script>");
// document.writeln("<script type='text/javascript' src='/static/cews_static/vendor/instascan/instascan.min.js'></script>");
var instascan;
$(function () {
    var is_play = false
    let check_button = $('#final_check_as_other')
    let check_button_text = $('#checkbutton-text')
    let username_span = $('#scaned_username')
    const csrf = $('input[name="csrfmiddlewaretoken"]').val()
    
    function getCheckState(){
        return $('#eform-action').val()
    }
    function resetUI(){
        check_button.attr('disabled',true)
        check_button_text.html('Scanning ...')
        username_span.html('')
        check_button.removeClass('btn-success')
        check_button.addClass('btn-primary')
    }

    function setUI(username){
        check_button.attr('disabled',false)
        check_button_text.html(`${getCheckState()} as `)
        username_span.html(username)
        check_button.addClass('btn-success')
        check_button.removeClass('btn-primary')
        // 
    }

    function setUser_id(user_id){
        $('#eform-user-id').val(user_id)
    }
    function unSetUser_id(){
        $('#eform-user-id').val('-1')
    }

    function getCheckUser(username_b64){
        data = new FormData()
        data.append("username",username_b64)
        data.append("check_state",getCheckState())
        return axios.post(getCheckUser_url,data,
        {
            headers:{
                "X-CSRFTOKEN":csrf
            }
        })
        
    }

    function setAlert(content) {
        html = `
        <div id="scan_modal__alert" class="alert alert-warning mb-0 alert-dismissible fade show" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
        </button>
        <strong id="scan_modal__alert__content">${content}</strong> 
        </div>
        `
        $('#scan_modal__alert').html(html)
    }

    instascan = function () {
        // console.log(id_stockcode, search_btn);

        let scanner = new Instascan.Scanner({ video: document.getElementById('preview'), mirror: false, });
        scanner.addListener('scan', function (content) {
            // alert(content);
            data = getCheckUser(content)
                .then(response=>{
                    data = response.data
                    if (!data.ack){
                        setAlert(data.err)
                        return
                    }
                    setUI(data.username)
                    setUser_id(data.user_id)
                })
            // check qr code has userkey
        });

        Instascan.Camera.getCameras().then(function (cameras) {
            if (cameras.length > 0) {
                scanner.start(cameras[cameras.length - 1]);
            } else {
                setAlert('No cameras found.');
            }
        }).catch(function (e) {
            console.error(e);
            setAlert('No cameras found.')
        });
// draw focus area on canvas
        function drawCanvas(){
            if (!is_play)
                return
            let canvas = document.getElementById('preview__canvas')
            let video = document.getElementById('preview')
            let ctx = canvas.getContext("2d")

            canvas.height = video.videoHeight
            canvas.width = video.videoWidth

            ctx.drawImage(video,0,0,canvas.width,canvas.height)

            var faceArea = 300;
            var pX=canvas.width/2 - faceArea/2;
            var pY=canvas.height/2 - faceArea/2;

            ctx.rect(pX,pY,faceArea,faceArea);
            ctx.lineWidth = "3";
            ctx.strokeStyle = "cyan";    
            ctx.stroke();

            setTimeout(drawCanvas,1000/30)
        }

        $('#preview').on('play',function(){
            is_play = true
            setTimeout(drawCanvas,300)
        })
        $('#preview').on('stop',_=>{
            is_play = false
        })

        $('#scan_modal').on('hide.bs.modal', function () {
            try {
                is_play=false
                $('#scan_modal__alert').html('')
                resetUI()
                unSetUser_id()
                scanner.stop()
            } catch {
                console.log("Erron while stopping scanner.")
            }
        })

    }
})